package cli;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.media.jai.JAI;

import omero.ServerError;

//import com.sun.media.imageio.plugins.tiff.TIFFImageWriteParam;
import com.sun.media.jai.codec.TIFFEncodeParam;

public class FileOperations {


	/**
	 * 
	 * @param fullFilename
	 * @param values
	 */
	public static void saveFile( String fullFilename, byte[] values ) 
			throws FileNotFoundException, IOException {
		OutputStream output = null;
		try {
			output = new BufferedOutputStream(new FileOutputStream( fullFilename ));
			output.write(values);
		} finally {
			System.out.println( "\tImage saved as " + fullFilename );
			output.close();
		}
	}

	
	/**
	 * Save from Omero (imageSrc) to file as TIFF
	 * Compression is not available
	 *  
	 * @param fullFilename
	 * @param imageSrc
	 * @throws IOException 
	 */
	public static void saveFileAsTIFF( String fullFilename, BufferedImage imageSrc ) throws ServerError,IOException {
		FileOutputStream os = new FileOutputStream( fullFilename );
		TIFFEncodeParam params =new TIFFEncodeParam();

		params.setCompression( TIFFEncodeParam.COMPRESSION_NONE );
		JAI.create( "encode", imageSrc, os, "TIFF", params );
		JAI.create( "filestore", imageSrc, fullFilename, "TIFF", params  );
		os.close();	
//		System.out.println( "File saved: " + fullFilename );
	}
		
	/**
	 * Generate the SHA1 code of the file
	 * @param datafile absolute path and filename (like "/images/40x.des") of the file
	 * @return 32 character string containing the sha1 code
	 * @throws NoSuchAlgorithmException 
	 */
	public static String generateSha1( String datafile ) 
			throws  FileNotFoundException, IOException, NoSuchAlgorithmException  {
   
	    MessageDigest md;
	    FileInputStream fis;

	    md = MessageDigest.getInstance("SHA1");
			fis = new FileInputStream(datafile);

		    byte[] dataBytes = new byte[1024];
		 
		    int nread = 0; 
		 
		    while ((nread = fis.read(dataBytes)) != -1) {
		      md.update(dataBytes, 0, nread);
		    }
		 
		    byte[] mdbytes = md.digest();

		    //convert the byte to hex format
		    StringBuffer sb = new StringBuffer("");
		    for (int i = 0; i < mdbytes.length; i++) {
		    	sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
		    }
		 
		    Logging.log( "Information", "Generated for file: " + datafile + " the SHA1 code of " +  sb.toString() );
		    return sb.toString();
			
	}
	
	/**
	 * Removes extension from the full filename
	 * @param fullname
	 * @return String with the file name body
	 */
	public static String filenameBody( String fullname ) {
		int pos = fullname.lastIndexOf('.');
		return fullname.substring( 0, pos );
	}
	
	/**
	 * Returns extension of the full file name
	 * @param fullname
	 * @return String with the file extension
	 */
	public static String filenameExtension( String fullname ) {
		int pos = fullname.lastIndexOf('.');
		if ( pos == -1 ) 
			return "";
		else
			return fullname.substring( pos+1, fullname.length() );
	}
	
	
	/** 
	 * Delete all files in a directory - Use with care!<br/>
	 * Mainly used for removing files in temp directories<br/>
	 * Assuming no subdirectories
	 * @return true if all files are deleted
	 */
	public static boolean deleteFilesInDir( File dir ) {
		if ( dir.isDirectory() ) {
			String[] children =  dir.list();
//			System.out.println( "Deleting " + children.length + " files in " + dir.getName()   );
			for ( int i=0; i < children.length; i++ ) {
				File child = new File( dir, children[i] );
				if ( ! child.delete() ) {
					return false;
				}
			}
		}	
		return true;
	}

}
